/**
*封装的工具类
*
*/ 

const request = require('request')
class WechatUtil {
    constructor(appid,secret) {
        this.reqUrl = "https://api.weixin.qq.com/sns/jscode2session"
        this.appid = appid
        this.secret = secret
        this.grant_type = "authorization_code"
        this.openId = null
        this.sessionKey = null
    }
    getOpenId(){
        return this.openId
    }
    getSessionKey(){
       return this.sessionKey
    }
    // 获取 sessionKey openid 
    async getSessionKeyOropenid(code) {
        return new Promise((resolve, reject) => {
            let url = `${this.reqUrl}?appid=${this.appid}&secret=${this.secret}&js_code=${code}&grant_type=${this.grant_type}`
            request.post(url, {}, (error, res, body) => {
                if (error) {
                    console.error(error)
                    reject(error)
                }
                if(res.statusCode == 200){
                    let jsonBody = JSON.parse(body)
                    this.openId = jsonBody.openId
                    this.sessionKey = jsonBody.session_key
                    if(jsonBody.errcode){
                        reject(jsonBody)
                    }
                    resolve(jsonBody)
                }
            })
        })
    }
    // // 解密获取用户信息
    // async getWechatUserInfo(encryptedData, ivv) {

    //         let key = CryptoJS.enc.Base64.parse(this.sessionKey)
    //         let iv = CryptoJS.enc.Base64.parse(ivv)
    //         let decrypt = CryptoJS.AES.decrypt(encryptedData, key, {
    //             iv: iv,
    //             mode: CryptoJS.mode.CBC,
    //             padding: CryptoJS.pad.Pkcs7
    //         })
    //         try {
    //             console.log(decrypt)
    //             return JSON.parse(Base64.decode(CryptoJS.enc.Base64.stringify(decrypt)))

    //         } catch (error) {
    //             console.log(error)
    //             return -10
    //         }
        
       
       
    // }
}

module.exports = WechatUtil
